<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of ModulesUsersTable
 *
 * @author root
 */

namespace Module\Model;
use Zend\Db\TableGateway\TableGateway;

class ModulesUsersTable {
    
    protected $tableGateway;

    public function getTableGateway() {
        return $this->tableGateway;
    }

    public function setTableGateway($tableGateway) {
        $this->tableGateway = $tableGateway;
    }

        
    public function __construct(TableGateway $tableGateway) {
        $this->tableGateway = $tableGateway;
    }
    
    public function isExist($uid, $mid)
    {
    	$where = new \Zend\Db\Sql\Where();
        
        $where->literal('uid = ? AND mid = ?', array($uid, $mid));
        
        if($this->tableGateway->select($where)->count())
        {
        	return true;
        }
        else
        {
        	return false;
        }
    }
    
    public function register($data)
    {
        if(!$this->isExist($data['uid'], $data['mid']))
        {
	    	$this->tableGateway->insert(array(
	                                        'uid'   => $data['uid'],
	                                        'mid'   => $data['mid'],
	                                        'state' => 1
	                                ));
        }
    }
    
    public function unregister($key)
    {
        if($this->isExist($key['uid'], $key['mid']))
        {
            $where = new \Zend\Db\Sql\Where();

            $where->literal('uid = ? AND mid = ?', array($key['uid'], $key['mid']));
            $this->tableGateway->delete($where);
        }
    }
    
    public function changeState($key, $state)
    {
        if($this->isExist($key['uid'], $key['mid']))
        {
            $where = new \Zend\Db\Sql\Where();
            $where->literal('uid = ? AND mid = ?', array($key['uid'], $key['mid']));
            $this->tableGateway->update(array('state' => $state), $where);
        }
        
    }
    public function getModulesUser($uid, $state = null)
    {
        if($state !== null)
        {
            $where = new \Zend\Db\Sql\Where();
            $where->literal('uid = ? AND state = ?', array($uid, $state));
            $resultSet = $this->tableGateway->select($where);
            return $resultSet->toArray();
        }
        else {
            $resultSet = $this->tableGateway->select(array('uid' => $uid));
            return $resultSet->toArray();
        }
    }
    
    public function getAll()
    {
        $resultSet = $this->tableGateway->select();
        return $resultSet->toArray();
    }
}

?>
